package com.neusoft.Shixun.controller;

import com.neusoft.Shixun.po.User;
import com.neusoft.Shixun.po.ResponseBean;
import com.neusoft.Shixun.service.RedisService;
import com.neusoft.Shixun.service.UserService;
import com.neusoft.Shixun.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/UserController")
@Tag(name = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;


    @Operation(summary = "登录", description = "用户登录，验证用户名和密码，成功后返回JWT令牌")
    @Parameters({
            @Parameter(name = "username", description = "账号", required = true),
            @Parameter(name = "password", description = "密码", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "登录成功", content = @Content(schema = @Schema(implementation = ResponseBean.class))),
            @ApiResponse(responseCode = "401", description = "用户名或密码错误")
    })
    @PostMapping("/login")
    public ResponseBean<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        // 验证用户登录信息
        ResponseBean<User> userResponseBean = userService.login(username, password);
        User user = userResponseBean.getData();
        if (user != null) {
            // 创建Claims
            Map<String, String> claims = new HashMap<>();
            claims.put("userId", user.getUserId().toString());
            claims.put("role", user.getRole());

            // 生成JWT令牌
            String token = JwtUtil.createToken(claims);
            System.out.println(token);

            // 返回令牌
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            return new ResponseBean<>(response);
        } else {
            return new ResponseBean<>(401, "用户名或密码错误");
        }
    }

    @Operation(summary = "退出登录", description = "用户退出登录，将JWT令牌加入黑名单")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "退出成功"),
            @ApiResponse(responseCode = "401", description = "未授权")
    })
    @PostMapping("/logout")
    public ResponseBean<Void> logout(@RequestHeader("Authorization") String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return new ResponseBean<>(401, "未授权");
        }

        String token = authorizationHeader.substring(7); // 去掉"Bearer "前缀
        redisService.addTokenToBlacklist(token);

        return new ResponseBean<>();
    }

    @Operation(summary = "获取所有用户", description = "获取系统中所有用户的信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = ResponseBean.class)))
    })
    @GetMapping("/getAllUsers")
    public ResponseBean<List<User>> getAllUsers() {
        return userService.getAllUsers();
    }

    @Operation(summary = "根据用户ID获取用户信息", description = "根据用户ID查询用户详细信息")
    @Parameter(name = "id", description = "用户ID", required = true)
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = ResponseBean.class))),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/{id}")
    public ResponseBean<User> getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

    @Operation(summary = "根据姓名查询用户信息", description = "根据姓名查询用户信息")
    @Parameter(name = "username", description = "管家姓名", required = true)
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = ResponseBean.class)))
    })
    @GetMapping("/getUserByName")
    public ResponseBean<User> getUserByName(@RequestParam String username) {
        return userService.getUserByName(username);
    }

    @Operation(summary = "根据管家姓名查询管家信息", description = "根据管家姓名查询管家信息")
    @Parameter(name = "careTakerName", description = "管家姓名", required = false)
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = ResponseBean.class)))
    })
    @GetMapping("/getUserByCareTakerName")
    public ResponseBean<List<User>> getUserByCareTakerName(@RequestParam(required = false) String careTakerName) {
        return userService.getUserByCareTakerName(careTakerName);
    }

    @Operation(summary = "添加用户", description = "添加新用户")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = ResponseBean.class)))
    })
    @PostMapping("/addUser")
    public ResponseBean<Integer> addUser(@RequestBody User user) {
        return userService.addUser(user);
    }

    @Operation(summary = "更新用户信息", description = "更新用户信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = ResponseBean.class)))
    })
    @PutMapping("/updateUser")
    public ResponseBean<Integer> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @Parameter(name = "id", description = "用户ID", required = true)
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = ResponseBean.class))),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @DeleteMapping("/{id}")
    public ResponseBean<Integer> deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }
}